<template>
      <div class="cart-container">
        <el-card class="box-card">
            <h2 style="display: flex; justify-content: center;">购物车</h2>

            <!-- 多选操作 -->
            <div class="top-opearations">
              <el-checkbox v-model="selectAll" @change="toggleSelectAll">全选</el-checkbox>
              <el-button style="width: 100px ;margin-left: 20px;" type="primary" size="small" @click="addSelectedToFavorites">转移到收藏夹</el-button>
              <el-button style="width: 100px ;margin-left: 20px;" type="danger" size="small" @click="removeSelectedItems">删除选中商品</el-button>
              <el-button style="width: 100px ;margin-left: 20px;" type="danger" size="small" @click="addSelectedToOrder">购买选中商品</el-button>
            </div>

            <!-- 数据加载中提示 -->
            <div v-if="loading" class="text-center text-gray-500">Loading...</div>
    
            <!-- 错误提示 -->
            <div v-else-if="error" class="text-center text-red-500">Failed to load cart data: {{ error }}</div>
            
          
            <!-- 购物车内容 -->
            <div v-else>
            <el-divider :border-style="'solid'"></el-divider>
            <div v-for="item in cartItems" :key="item.goodId" class="space-y-6">
                <div class="shopping-cart-item">
                <!-- 选择框 -->
                <el-checkbox v-model="selectedItems" :label="item.goodId" />
                <!-- 商品图片 -->
                <el-image
                    class="image"
                    :src="item.imageUrl"
                    :alt="item.name"
                    fit="contain"
                />
                <div class="detail-item">
                <div class="info-item">
                    <div class="name-item"><p class="text-base font-medium text-gray-900 truncate">{{ item.name }}</p></div>
                <div class="price-item">
                    <!-- 商品信息 -->
                <div class="flex-1 space-y-2 md:ml-6">
                    <p class="text-sm text-gray-500">单价: ￥{{ item.price.toFixed(2) }}</p>
                </div>

                <!-- 总价 -->
                <div class="w-24 text-right md:w-32">
                    <p class="mr-2 text-sm text-gray-500">总价:￥{{ (item.price * item.quantity).toFixed(2) }}</p>
                </div>

                </div>    
                </div>
                
    
                <!-- 数量选择器 -->
                <div class="number">
                    <el-input-number
                    v-model="item.quantity"
                    :min="1"
                    :max="100"
                    size="small"
                    @change="updateQuantity(item.goodId, item.quantity)"
                    />
                </div>
                
                <div class="operations">
                <!-- 操作按钮 -->
                    <el-button type="text" size="small" @click="addToFavorites(item)" class="text-yellow-600">收藏
                    </el-button>
                    <el-button type="text" size="small" @click="removeItem(item.goodId)" class="text-red-600">删除
                    </el-button>
                    <el-button type="text" size="small" @click="addToOrder(item.goodId)" class="text-red-600">购买
                    </el-button>
                </div>
                </div>
                </div>
                <el-divider :border-style="'solid'"></el-divider>
            </div>
            </div>
        </el-card>
      </div>
  </template>
  
  
  <script>
  import { addToFavorites,removeFromCart ,updateGoodsQuantity ,addToOrder} from "@/apis/cart";
  import { useUserStore } from "@/stores/user";

  export default {
    props: {
      cartItems: Array,
      loading: Boolean,
      error: String,
    },
    data() {
      return {
        selectedItems: [], // 选中的商品 goodId 列表
        selectAll: false, // 全选状态
      };
    },
    watch: {
      // 同步全选状态
      selectAll(val) {
        this.selectedItems = val ? this.cartItems.map((item) => item.goodId) : [];
      },
      // 同步 selectedItems 和 cartItems 的变化
      selectedItems(val) {
        this.selectAll = val.length === this.cartItems.length;
      },
    },
    setup() {
      const userStore = useUserStore();
      const userId = userStore.userAInfo.userId; // 从 Pinia 获取 userId
      return {
        userId,
      };
    },
    methods: {
      // 单个商品添加到收藏夹
      async addToFavorites(item) {
        try {
          if (!this.userId) throw new Error("Customer ID not found.");
          // console.log([item.goodId]);
          await addToFavorites([item.goodId], this.userId);
          this.$message.success(`${item.name} added to favorites.`);
        } catch (err) {
          this.$message.error(err.message || "Failed to add to favorites.");
        }
      },
      //单个商品下单
      async addToOrder(item) {
        try {
          if (!this.userId) throw new Error("Customer ID not found.");
          await addToOrder([item.goodId], this.userId);
          this.$message.success("选择商品已成功下单");
          this.$message.success(`${item.name} added to order.`);
        } catch (err) {
          this.$message.error(err.message || "Failed to add to order.");
        }
      },
      // 批量添加到收藏夹
      async addSelectedToFavorites() {
        if (this.selectedItems.length === 0) {
          this.$message.warning("请选择至少一个商品");
          return;
        }
        try {
          // const customerId = localStorage.getItem("customerId");
          if (!this.userId) throw new Error("Customer ID not found.");
          await addToFavorites(this.selectedItems, this.userId);
          this.$message.success("选择商品已成功转移到收藏夹");
          // 更新购物车数据
          this.$emit("update-cart");
        } catch (err) {
          this.$message.error(err.message || "转移到收藏夹失败");
        }
      },
      //商品批量下单
      async addSelectedToOrder() {
        if (this.selectedItems.length === 0) {
          this.$message.warning("请选择至少一个商品");
          return;
        }
        try {
          // const customerId = localStorage.getItem("customerId");
          if (!this.userId) throw new Error("Customer ID not found.");
          await addToOrder(this.selectedItems,this.userId);
          this.$message.success("选择商品已成功下单");
        }catch (err) {
          this.$message.error(err.message || "商品下单失败");
        }
      },
      // 单个商品从购物车中删除
    async removeItem(goodId) {
      try {
        if (!this.userId) throw new Error("Customer ID not found.");
        await removeFromCart([goodId], this.userId);
        this.$message.success("Item removed from cart.");
        this.$emit("update-cart");
      } catch (err) {
        this.$message.error(err.message || "Failed to remove item from cart.");
      }
    },

    // 批量删除选中的商品
    async removeSelectedItems() {
      if (this.selectedItems.length === 0) {
        this.$message.warning("Please select at least one item.");
        return;
      }
      try {
        if (!this.userId) throw new Error("Customer ID not found.");
        await removeFromCart(this.selectedItems, this.userId);
        this.$message.success("Selected items removed from cart.");
        this.$emit("update-cart");
      } catch (err) {
        this.$message.error(err.message || "Failed to remove selected items from cart.");
      }
    },
    // 更新商品数量
    async updateQuantity(goodId, quantity) {
        try {
            if (!this.userId) throw new Error("Customer ID not found.");
            await updateGoodsQuantity(this.userId ,goodId, quantity);
            // 处理成功响应
            this.$message.success("商品数量更新成功");
            this.$emit("update-cart");
        } catch (error) {
            // 处理错误
            this.$message.error(error.message ? error.response.data : error.message || "更新商品数量失败");
        }
    },
    },
  };
  </script>
  
  
  <style scoped>
  /* 添加自定义样式 */
  .cart-container {
    display: flex;
    justify-content: center;
    /* align-items: center; */
    height: 100%;
  }

  .box-card{
    width: 80%;
    justify-content: center;
  }
  .top-operations{
    display: flex;
    flex-direction: column;
    /* justify-content: space-between; */
    /* align-items: center; */
  }
  .shopping-cart-item {
    width: 100%;
    height: 20%;
    margin-bottom: 20px;
    display: flex;
  }
 .detail-item{
    display: flex;
    /* flex-direction: column; */
    width: 100%;
    margin-left: 50px;
    /* background-color: blanchedalmond; */
  }
  .info-item{
    width: 100%;
    margin-left: 30px;
    /* background-color: aqua; */
  }
  .name-item{
    width: 50%;
    margin-top: 30px;
    /* background-color: cadetblue; */
  }
  .price-item{
    margin-left: 25px;
    margin-top: 40px;
    width: 100px;
    font-size: small;
    /* background-color: rgb(223, 128, 12) */
  }
  .number{
    margin-right: 120px;
    margin-top: 80px;
    /* background-color: blueviolet; */
  }
  .operations{
    margin-top: 80px;
    margin-right: 80px;
    display: flex;
    /* flex-direction: column; */
    /* background-color: chartreuse; */
  }
  .image{
    width: 200px;
    margin-left: 50px;
    border-radius: 10%;
  }
  </style>
  